package ru.btabank.dom.xpath.expression;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import ru.btabank.dom.util.DOMUtil;

public class CommentStep extends Step {
    public CommentStep() {
    }

    public NodeSet select(NodeSet source) {
        NodeSet target;
        Node sourceNode, childNode;
        NodeList childNodes;

        target = new NodeSet();
        for (int sourceIndex = 0; sourceIndex < source.getLength(); sourceIndex++) {
            sourceNode = source.item(sourceIndex);
            childNodes = sourceNode.getChildNodes();
            for (int childIndex = 0; childIndex < childNodes.getLength(); childIndex++) {
                childNode = childNodes.item(childIndex);
                if (childNode.getNodeType() == Node.COMMENT_NODE) {
                    target.add(childNode);
                }
            }
        }
        return target;
    }

    public NodeSet build(NodeSet source) {
        NodeSet target, temp;
        Node sourceNode, childNode;
        NodeList childNodes;

        target = new NodeSet();
        temp = new NodeSet();
        for (int sourceIndex = 0; sourceIndex < source.getLength(); sourceIndex++) {
            sourceNode = source.item(sourceIndex);
            childNodes = sourceNode.getChildNodes();
            for (int childIndex = 0; childIndex < childNodes.getLength(); childIndex++) {
                childNode = childNodes.item(childIndex);
                if (childNode.getNodeType() == Node.COMMENT_NODE) {
                    temp.add(childNode);
                }
            }
            if (temp.getLength() == 0) {
                childNode = DOMUtil.createComment(sourceNode);
                temp.add(childNode);
            }
            target.add(temp);
            temp.clear();
        }
        return target;
    }

    public String toString() {
        return "comment()";
    }
}
